﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SalaryChannel.TaskWebService;

namespace SalaryChannel
{
    public partial class TaskManagement : UserControl
    {
        //TaskWebService.ServiceInstance.TaskServiceClient ServiceInstance.TaskService = ServiceInstance.ServiceInstance.TaskService;
        public TaskManagement()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(TaskManagement_Loaded);

            ServiceInstance.TaskService.GetTaskStatusCompleted += new EventHandler<GetTaskStatusCompletedEventArgs>(TaskService_GetTaskStatusCompleted);
            ServiceInstance.TaskService.StartTaskCompleted += new EventHandler<StartTaskCompletedEventArgs>(TaskService_StartTaskCompleted);
            ServiceInstance.TaskService.GetTaskFlowCompleted += new EventHandler<GetTaskFlowCompletedEventArgs>(TaskService_GetTaskFlowCompleted);
            TaskMngmtGrid.LoadingRow += new EventHandler<DataGridRowEventArgs>(TaskMngmtGrid_LoadingRow);
            TaskFlowGrid.LoadingRow += new EventHandler<DataGridRowEventArgs>(TaskFlowGrid_LoadingRow);
        }

        void TaskFlowGrid_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            SP_TaskFlow_个结果 flow = e.Row.DataContext as SP_TaskFlow_个结果;
            TextBlock tb = TaskFlowGrid.Columns[4].GetCellContent(e.Row) as TextBlock;
           // int hours = int.Parse(tb.Text);
            if (flow.Left_Hours >= 10)
            {
                tb.Foreground = new SolidColorBrush(Colors.Green);
            }
            else if (flow.Left_Hours < 10 && flow.Left_Hours >= 0)
            {
                tb.Foreground = new SolidColorBrush(Colors.Red);

            }
            else
            {
                tb.Foreground = new SolidColorBrush(Colors.Black);
            }
        }

        void TaskMngmtGrid_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            SP_TaskStatus_个结果 status= e.Row.DataContext as SP_TaskStatus_个结果;
           TextBlock tb= TaskMngmtGrid.Columns[2].GetCellContent(e.Row) as TextBlock;
           if (status.Status == "未启动")
           {
               tb.Foreground = new SolidColorBrush(Colors.Red);

           }
           else if (status.Status == "进行中")
           {
               tb.Foreground = new SolidColorBrush(Colors.Green);
           }
           else 
           {
               tb.Foreground = new SolidColorBrush(Colors.Black);

           }

        }

        

        void TaskManagement_Loaded(object sender, RoutedEventArgs e)
        {
            DateTime now = DateTime.Now;
            int Months = -1;
            while (Months >-12)
            {
                DateTime dt = now.AddMonths(Months);
                this.MonthCBox.Items.Add(dt.Year * 100 + dt.Month);
                Months--;
            }

        }

        public void Initiallize()
        {
            TaskMngmtGrid.Visibility = Visibility.Visible;
            TaskFlowGrid.Visibility = Visibility.Collapsed;
            this.TaskMngmtGrid.ItemsSource = null;
            this.TaskFlowGrid.ItemsSource = null;
            this.MonthCBox.SelectedIndex = -1;
            this.TaskFlowGrid.Tag = null;
        }

        /// <summary>
        /// 选择月份后展示酬金任务状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MonthCBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (MonthCBox.SelectedIndex < 0)
            {
                return;
            }
            try
            {
                ServiceInstance.TaskService.GetTaskStatusAsync(int.Parse(MonthCBox.SelectedItem.ToString()), Guid.NewGuid());
                this.Cursor = Cursors.Wait;
            }
            catch (Exception ex)
            {

                App.MessageBox.ShowDialog("发起查询请求异常:" + ex.Message, Title.Error);
                this.Cursor = Cursors.Arrow;
            }
        }
        void TaskService_GetTaskStatusCompleted(object sender, GetTaskStatusCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("查询任务状态失败,服务器异常",Title.Error);
                }
                else
                {
                    this.TaskMngmtGrid.ItemsSource = e.Result;
                }
            }
            catch (Exception ex)
            {

                App.MessageBox.ShowDialog("查询任务状态失败:" + ex.Message, Title.Error);
            }
            finally
            {
                this.Cursor = Cursors.Arrow;
            }

        }

        /// <summary>
        /// 启动选中的任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StartBtn_Click(object sender, RoutedEventArgs e)
        {
            if (!App.IsAuth(16))
            {
                App.MessageBox.ShowDialog("您无权启动新任务");
                return;
            }
            if (this.TaskMngmtGrid.SelectedItem == null
                || (TaskMngmtGrid.SelectedItem as SP_TaskStatus_个结果).Status!="未启动")
            {
                App.MessageBox.ShowDialog("请选择一个未启动的任务", Title.Warning);
                return;
            }
          SP_TaskStatus_个结果 selected=  (TaskMngmtGrid.SelectedItem as SP_TaskStatus_个结果);
          App.MessageBox.ShowDialog(string.Format("是否启动任务：[{0}]{1}?", selected.Task_ID, selected.Name),
              new Action(DoStartTask), Title.Information);
           
        }

        private void DoStartTask()
        {
            try
            {
                ServiceInstance.TaskService.StartTaskAsync((TaskMngmtGrid.SelectedItem as SP_TaskStatus_个结果).Task_ID,
                       int.Parse(MonthCBox.SelectedItem.ToString()),
                       App.CurrentUser.UserID, Guid.NewGuid());
           
                    this.Cursor = Cursors.Wait;
            }
            catch (Exception ex)
            {

                App.MessageBox.ShowDialog("发起请求异常:" + ex.Message, Title.Error);
                this.Cursor = Cursors.Arrow;
            }
        }


        void TaskService_StartTaskCompleted(object sender, StartTaskCompletedEventArgs e)
        {
            if (e.Result)
            {
                MonthCBox_SelectionChanged(null, null);
                App.MessageBox.ShowDialog("启动任务成功");
            }
            else
            {
                App.MessageBox.ShowDialog("启动任务失败，服务器异常");
            }
            this.Cursor = Cursors.Arrow;

        }

        /// <summary>
        /// 显示任务流程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ShowFlowBtn_Click(object sender, RoutedEventArgs e)
        {
            if(TaskMngmtGrid.SelectedItem  == null)
            {
                App.MessageBox.ShowDialog("请选择一个任务",Title.Warning);
                return;
            }
            SP_TaskStatus_个结果 status = (TaskMngmtGrid.SelectedItem as SP_TaskStatus_个结果);
            if (status.Status == "未启动")
            {
                App.MessageBox.ShowDialog("该任务未启动，无法显示流程", Title.Warning);
                return;
            }
            string Tag = string.Format("[{0}]{1}", status.Task_ID, MonthCBox.SelectedItem);
            if (!Tag.Equals(this.TaskFlowGrid.Tag))
            {
                try
                {
                    ServiceInstance.TaskService.GetTaskFlowAsync(status.Task_ID, int.Parse(MonthCBox.SelectedItem.ToString()));
                }
                catch (Exception ex)
                {
                    App.MessageBox.ShowDialog("发起查询请求异常:" + ex.Message, Title.Error);
                    return;
                }
                this.TaskFlowGrid.Tag = string.Format("[{0}]{1}", status.Task_ID, MonthCBox.SelectedItem);
            }
            this.TaskMngmtGrid.Visibility = Visibility.Collapsed;
            this.TaskFlowGrid.Visibility = Visibility.Visible;
        }
        void TaskService_GetTaskFlowCompleted(object sender, GetTaskFlowCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("获取任务流程失败，服务器异常");
                }
                else
                {
                    this.TaskFlowGrid.ItemsSource = e.Result;
                }
            }
            catch
            {
                
                App.MessageBox.ShowDialog("获取任务流程失败，服务器异常");
            }
        }

        private void BackBtn_Click(object sender, RoutedEventArgs e)
        {
            if (TaskMngmtGrid.Visibility == Visibility.Collapsed)
            {
                this.TaskMngmtGrid.Visibility = Visibility.Visible;
                this.TaskFlowGrid.Visibility = Visibility.Collapsed;
            }
        }
    }
}
